<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); 

global $mosConfig_live_site;

define('FEDEX_REQUEST_REFERER', $mosConfig_live_site);
define('FEDEX_REQUEST_TIMEOUT', 20);
define('FEDEX_IMG_DIR', '/tmp/');

class mondialrelay {

    var $classname = 'mondialrelay';

	// $config_array contains all variable names for the configuration page
    var $config_array = array (
				'MR_ENSEIGNE'
				,'MR_MARQUE'
				,'MR_CLE'
				,'MR_MARQUE_URL'
				,'MR_CLE_URL'
				,'MR_ENSEIGNE_ADDRESSE1'
				,'MR_ENSEIGNE_ADDRESSE3'
				,'MR_ENSEIGNE_ADDRESSE4'
				,'MR_ENSEIGNE_CP'
				,'MR_ENSEIGNE_VILLE'
				,'MR_ENSEIGNE_PAYS'
				,'MR_ENSEIGNE_TEL'
				,'MR_ENSEIGNE_MOBILE'
				,'MR_ENSEIGNE_MAIL'
    	);
    	
	
	/** 
	 * Echos a formatted list of shipping rates.
	 * 
	 * @param array $d
	 * @return boolean
	 */
    function list_rates( &$d ) {
		global $vendor_country_2_code, $vendor_currency, $vmLogger;
		global $VM_LANG, $CURRENCY_DISPLAY;
		
		// Read the mondialrelay configuration file
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
		
		if( defined( __CLASS__ . '_list_mondialrelay_rates_called' ) ) {
			return ;
		}
		// Prevent that list_rates is called more than once
		// as this is a fallback method when other classes fail to
		// list their rates
		define( __CLASS__ . '_list_mondialrelay_rates_called', 1 );
		
		$dbc = new ps_DB( ) ; // Carriers
		$dbr = new ps_DB( ) ; // Rates
		$dbs = new ps_DB( ) ; // Shipping_Currensy

		$selected = False ;
		$d['ship_to_info_id'] = vmGet( $_REQUEST, 'ship_to_info_id' ) ;
		$q  = "SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_info_id='" . $d["ship_to_info_id"]."' AND ( country=country_2_code OR country=country_3_code)";
		$dbc->query( $q ) ;
		$dbc->next_record() ;
		
		$zip = $dbc->f( "zip" ) ;
		$country = $dbc->f( "country_2_code" ) ;

		$cart = $_SESSION['cart'];

		// Get the weight total
		if( $d['weight'] < 0.100) {
			$d['weight'] = 0.100;
		}
		
		$q = "SELECT shipping_rate_id,shipping_rate_name,shipping_rate_value,shipping_rate_package_fee,shipping_rate_currency_id FROM #__{vm}_mondialrelay_shipping_rate WHERE " ;
		$q .= "shipping_rate_carrier='MONDIALRELAY' AND " ;
		$q .= "(shipping_rate_country LIKE '%" . $country . "%' OR " ;
		$q .= "shipping_rate_country = '') AND " ;
		if( is_numeric( $zip ) ) {
			$q .= "(shipping_rate_zip_start <= '" . $zip . "' OR  LENGTH(shipping_rate_zip_start) = 0 ) AND " ;
			$q .= "(shipping_rate_zip_end >= '" . $zip . "' OR  LENGTH(shipping_rate_zip_end) = 0 ) AND " ;
		}
		$q .= "shipping_rate_weight_start <= '" . $d["weight"] . "'AND " ;
		$q .= "shipping_rate_weight_end >= '" . $d["weight"] . "'" ;
		$q .= " ORDER BY shipping_rate_value " ;
		
		$dbr->query( $q ) ;
		
		// On met en place les paramÃ¨tres de la requÃ¨te
		$params = array(
					   'Enseigne'     => MR_ENSEIGNE,
					   'Pays'         => $country,
					   'CP'           => $zip,
		);
		
		//On crÃ©e le code de sÃ©curitÃ©
		$code = implode("",$params);
		$code .= MR_CLE;
				
		//On le rajoute aux paramÃ¨tres
		$params["Security"] = strtoupper(md5($code));
				
		// On se connecte
		$client = new SoapClient("http://www.mondialrelay.fr/WebService/Web_Services.asmx?WSDL");
				
		// Et on effectue la requÃ¨te
		$points_relais = $client->WSI2_RecherchePointRelais($params)->WSI2_RecherchePointRelaisResult;
				
		
		// Get the rate quote
		//rate_Ret = $fed->services_rate ( $request_array );		
		
		$html = '';
		// On crée une méthode de livraison par point relais
		if($dbr->num_rows() && count($points_relais)){
			$html = "<table width=\"100%\">\n<tr class=\"sectiontableheader\"><th>&nbsp;</th><th>" ;
			$html .= $VM_LANG->_('PHPSHOP_INFO_MRPR_SHIPPING_PRICE') . "</th><th>" ;
			$html .= $VM_LANG->_('PHPSHOP_INFO_MSG_SHIPPING_PRICE') . "</th></tr>\n" ;
		}
		
		$link = $mosConfig_live_site .'/index2.php?option=com_virtuemart&amp;page=shop.mondialrelay&amp;pop=1&amp;hauteur=450&amp;largeur=800&amp;ship_to_info_id='.$d['ship_to_info_id'].'&amp;id_relais=';
		
		
		
		while( $dbr->next_record() ) {
			foreach( $points_relais as $point_relais ) {
				//echo 'test:'.count($points_relais);
				if ( is_object($point_relais) && trim($point_relais->Num) != '' ) {
					if( $_SESSION['auth']['show_price_including_tax'] != 1 ) {
						$taxrate = 1 ;
					} else {
						$taxrate = $this->get_tax_rate( $dbr->f( "shipping_rate_id" ) ) + 1 ;
					}
					

					// Select shipping_rate_currency_code
					$q = "SELECT currency_code FROM #__{vm}_currency WHERE currency_id ='" . $dbr->f( "shipping_rate_currency_id" ) . "'" ;
					$dbs->query( $q ) ;
					

					if( $dbs->next_record() ) {
						$shipping_rate_currency_code = $dbs->f( "currency_code" ) ;
					}
	
					$total_shipping_handling = $dbr->f( "shipping_rate_value" ) + $dbr->f( "shipping_rate_package_fee" ) ;
					$total_shipping_handling = $GLOBALS['CURRENCY']->convert( $total_shipping_handling, $shipping_rate_currency_code, $GLOBALS['product_currency'] ) ;
					$total_shipping_handling *= $taxrate ;
					$show_shipping_handling = $CURRENCY_DISPLAY->getFullValue( $total_shipping_handling ) ;
					
					$html .= '<tr \">' ;
					$shipping_rate_id = urlencode( __CLASS__ . "|MONDIALRELAY|" . $point_relais->Num . "|" . number_format( $total_shipping_handling, 2, '.', '' ) . "|" . $dbr->f( "shipping_rate_id" ) ) ;
					$_SESSION[$shipping_rate_id] = 1 ;
					
					
					$popup_params = array(
								   'ens'     => MR_MARQUE_URL,
								   'num'     => $point_relais->Num,
								   'pays'    => $country,
					);
					
					
					$popup_code = '<'.MR_MARQUE_URL.'>'.$point_relais->Num.$country.'<'.MR_CLE.'>';
							
					
					$popup_params["Security"] = strtoupper(md5($popup_code));
					
					$link = 'http://www.mondialrelay.com/lg_fr/espaces/url/popup_pointrelais.aspx?ens='. $popup_params["ens"] .'&num='.$popup_params["num"].'&pays='.$popup_params["pays"].'&crc='.$popup_params["Security"];
					
					$html .= "<td width=\"10\"><input type=\"radio\" id=\"shipping_rate_id_mr_" . $point_relais->Num . "\" name=\"shipping_rate_id\" value=\"" . $shipping_rate_id . "\" " ;
					$html .= " /></td>" ;
					$html .= '<td>' . $point_relais->LgAdr1 . ' - ' . $point_relais->Ville  . ' '.vmPopupLink( $link, 'D&eacute;tails', '800', '450' ).'</td>' ;
					
				
					
				
					$html .= "<td>" . $show_shipping_handling . "</td></tr>\n" ;
				}
			}
		}
		if(count($points_relais)){
			$html .= "</table>\n" ;
		}
		echo $html;

		return true;
    }
    /**
	 * returns the money to payfor from the given rate id
	 *
	 * @param array $d
	 * @return array
	 */
	function get_rate_details( &$d ) {
		
		$rvalue["pure_rate"] = 0 ;
		$rvalue["pack_rate"] = 0 ;
		$rvalue["total_rate"] = 0 ;
		$rvalue["vat_rate"] = 0 ;
		$rvalue["vat_value"] = 0 ;
		$rvalue["rate_curr"] = 0 ;
		
		$details = explode( "|", urldecode( $d['shipping_rate_id'] ) ) ;
		$rate_id = $details[4] ;
		
		$dbr = new ps_DB( ) ; // Rates
		$q = "SELECT * FROM #__{vm}_mondialrelay_shipping_rate WHERE " ;
		$q .= "shipping_rate_id='$rate_id'" ;
		$dbr->query( $q ) ;
		if( $dbr->next_record() ) {
			$rvalue["name"] = $dbr->f( "shipping_rate_name" ) ;
			$rvalue["carrier"] = $dbr->f( "shipping_rate_name" ) ;
			$rvalue["pure_rate"] = $dbr->f( "shipping_rate_value" ) ;
			$rvalue["total_rate"] = $dbr->f( "shipping_rate_value" ) ;
			$rvalue["vat_id"] = $dbr->f( "shipping_rate_vat_id" ) ;
			if( TAX_MODE == '1' ) {
				$dbv = new ps_DB( ) ;
				$q = "SELECT * FROM #__{vm}_tax_rate WHERE tax_rate_id ='" . $dbr->f( "shipping_rate_vat_id" ) . "'" ;
				$dbv->query( $q ) ;
				if( $dbv->next_record() ) {
					$rvalue["vat_rate"] = $dbv->f( "tax_rate" ) ;
					$rvalue["vat_value"] = ($rvalue["total_rate"] * $rvalue["vat_rate"]) / (100 + $rvalue["vat_rate"]) ;
				}
			}
			
			$q = "SELECT * FROM #__{vm}_currency WHERE currency_id ='" . $dbr->f( "shipping_rate_currency_id" ) . "'" ;
			$dbc->query( $q ) ;
			if( $dbc->next_record() ) {
				$rvalue["rate_curr"] = $dbc->f( "currency_code" ) ;
			}
		}
		return $rvalue ;
	}
    	
 	/**
 	 * Return the rate amount
 	 *
 	 * @param array $d
 	 * @return float Shipping rate value
 	 */
	function get_rate( &$d ) {

		$shipping_rate_id = $d["shipping_rate_id"];
		$is_arr = explode("|", urldecode(urldecode($shipping_rate_id)) );
		$order_shipping = $is_arr[3];

		return $order_shipping;

	} //end function get_rate
	
	/**
	 * Retrieves the tax rate to apply to a shipping rate
	 *
	 * @param int $shipping_rate_id
	 * @return float
	 */
	function get_tax_rate( $shipping_rate_id = 0 ) {
		$database = new ps_DB( ) ;
		
		// added by sobers_2002 to fix the issue with shipping tax being calculated for non-state orders
		$db = new ps_DB();
		$ship_to_info_id = vmGet( $_REQUEST, 'ship_to_info_id');
		$q = "SELECT state, country FROM #__{vm}_user_info ";
		$q .= "WHERE user_info_id='".$ship_to_info_id. "'";
		$db->query($q);
		$db->next_record();
		$state = $db->f("state");
		
		if( $shipping_rate_id == 0 ) {
			$shipping_rate_id = vmGet( $_REQUEST, "shipping_rate_id" ) ;
			$ship_arr = explode( "|", urldecode( urldecode( $shipping_rate_id ) ) ) ;
			$shipping_rate_id = (int)$ship_arr[4] ;
		}
		
		$q = "SELECT tax_rate FROM #__{vm}_mondialrelay_shipping_rate,#__{vm}_tax_rate WHERE shipping_rate_id='$shipping_rate_id' AND shipping_rate_vat_id=tax_rate_id"; 
		
		// check if state tax is applicable to the user
		if ($state) {
			$q .= " AND tax_state = '" . $state . "'";
		}

		$database->query($q);
		$database->next_record() ;
		if( $database->f( 'tax_rate' ) ) {
			return $database->f( 'tax_rate' ) ;
		} else {
			return 0.00 ;
		}
	}
		/**
	 * Validate a selected Shipping Rate
	 *
	 * @param array $d
	 * @return boolean
	 */
	function validate( &$d ) {
		global $VM_LANG, $vmLogger ;
		$cart = $_SESSION['cart'] ;
		//$shipping_rate_id = urlencode( __CLASS__ . "|MONDIALRELAY|" . $point_relais->Num . "|" . number_format( $total_shipping_handling, 2, '.', '' ) . "|" . $dbr->f( "shipping_rate_id" ) ) ;
		$d['shipping_rate_id'] = vmGet( $_REQUEST, 'shipping_rate_id' ) ;
		$d['ship_to_info_id'] = vmGet( $_REQUEST, 'ship_to_info_id' ) ;
		
		if( empty( $_SESSION[$d['shipping_rate_id']] ) ) {
			return false ;
		}
		
		$details = explode( "|", urldecode( $d['shipping_rate_id'] ) ) ;
		$rate_id = intval( $details[4] ) ;
		
		$totalweight = 0 ;
		require_once (CLASSPATH . 'ps_shipping_method.php') ;
		for( $i = 0 ; $i < $cart["idx"] ; $i ++ ) {
			$weight_subtotal = ps_shipping_method::get_weight( $cart[$i]["product_id"] ) * $cart[$i]['quantity'] ;
			$totalweight += $weight_subtotal ;
		}
		
		
		$dbu = new ps_DB( ) ; //DB User
		$q  = "SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_info_id='" . $d["ship_to_info_id"]."' AND ( country=country_2_code OR country=country_3_code)";
		$dbu = new ps_DB( ) ; //DB User
		$dbu->query( $q ) ;
		if( ! $dbu->next_record() ) {
			/*$vmLogger->err( $VM_LANG->_('PHPSHOP_CHECKOUT_ERR_SHIPTO_NOT_FOUND',false) );
			return False;*/
		}
		
		$zip = $dbu->f( "zip" ) ;
		$country = $dbu->f( "country_2_code" ) ;
		
		$q = "SELECT shipping_rate_id FROM #__{vm}_mondialrelay_shipping_rate WHERE shipping_rate_id = '$rate_id'" ;
		$dbs = new ps_DB( ) ; // DB Shiping_rate
		$dbs->query( $q ) ;
		if( ! $dbs->next_record() ) {
//			$vmLogger->err( $VM_LANG->_('PHPSHOP_CHECKOUT_ERR_RATE_NOT_FOUND',false) ) ;
//			return False ;
		}
		
		return $this->rate_id_valid( $rate_id, $country, $zip, $totalweight ) ;
	}
/**
	 * checks if the rate is valid for the country, zip and weight
	 *
	 * @param int $rate_id
	 * @param string $country
	 * @param int $zip
	 * @param float $weight
	 * @return boolean
	 */
	function rate_id_valid( $rate_id, $country, $zip, $weight ) {
		global $VM_LANG, $vmLogger ;
		$db = new ps_DB( ) ; // Rates
		$q = "SELECT * FROM #__{vm}_mondialrelay_shipping_rate WHERE shipping_rate_id=$rate_id" ;
		
		$db->query( $q ) ;
		if( $db->next_record() ) {
			$valid = true ;
			if( ! stristr( $db->f( "shipping_rate_country" ), $country ) && $db->f( 'shipping_rate_country' ) != "" ) {
				$vmLogger->debug( 'The country ' . $country . ' is not supported by this shipping rate.' ) ;
				$valid = false ;
			}
			if( $db->f( "shipping_rate_weight_start" ) > $weight ) {
				$vmLogger->debug( 'The weight ' . $weight . ' is not enough for this shipping rate.' ) ;
				$valid = false ;
			
			}
			if( $db->f( "shipping_rate_weight_end" ) < $weight ) {
				$vmLogger->debug( 'The weight ' . $weight . ' is too high for this shipping rate.' ) ;
				$valid = false ;
			
			}
			if( is_numeric( $zip ) ) {
				if( $db->f( "shipping_rate_zip_start" ) > $zip ) {
					$vmLogger->debug( 'The ZIP ' . $zip . ' is smaller than the supported ZIP code range of this shipping rate.' ) ;
					$valid = false ;
				
				}
				if( $db->f( "shipping_rate_zip_end" ) < $zip ) {
					$vmLogger->debug( 'The ZIP ' . $zip . ' is higher than the supported ZIP code range of this shipping rate.' ) ;
					$valid = false ;
				}
			}
			if( ! $valid ) {
				$vmLogger->err( $VM_LANG->_('PHPSHOP_CHECKOUT_ERR_OTHER_SHIP',false) ) ;
			}
			return $valid ;
		
		} else {
			$vmLogger->debug( 'The rate id ' . $rate_id . ' is not a valid shipping rate' ) ;
			return false ;
		}
	}

	/**
    * Show all configuration parameters for this Shipping method
    * @returns boolean False when the Shipping method has no configration
    */
	function show_configuration() {

		global $VM_LANG;
		
		$db =& new ps_DB;
        $q  = "SELECT * FROM #__{vm}_country";
        $db->query($q);
        $countryArray = array();
        while($db->next_record()){
               $countryArray[$db->f('country_2_code')] = $db->f('country_name');
        }
        
        // Select shipping_rate_currency_code
        
		$q = "SELECT currency_code,currency_id FROM #__{vm}_currency" ;
		$db->query( $q ) ;
        $currencyArray = array();
        while($db->next_record()){
        	$currencyArray[$db->f('currency_id')] = $db->f( "currency_code" );
        }
        
		// Read the mondialrelay configuration file
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
	    ?>
<div style="width:80%;padding:0 10px;">
	<table class="adminform">
		<th colspan="3"><?php echo $VM_LANG->_('VM_MR_ACCOUNT_SETTINGS') ?></th>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_ENSEIGNE_TIP')) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE" class="inputbox" value="<?php echo MR_ENSEIGNE ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_MARQUE_TIP')) ?><?php echo $VM_LANG->_('VM_MR_MARQUE') ?> (*)</td>
			<td><input type="text" name="MR_MARQUE" class="inputbox" value="<?php echo MR_MARQUE ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_CLE_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_CLE') ?> (*)</td>
			<td><input type="text" name="MR_CLE" class="inputbox" value="<?php echo MR_CLE ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_MARQUE_URL_TIP')) ?><?php echo $VM_LANG->_('VM_MR_MARQUE_URL') ?> (*)</td>
			<td><input type="text" name="MR_MARQUE_URL" class="inputbox" value="<?php echo MR_MARQUE_URL ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_CLE_URL_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_CLE_URL') ?> (*)</td>
			<td><input type="text" name="MR_CLE_URL" class="inputbox" value="<?php echo MR_CLE_URL ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE1_TIP')) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE1') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_ADDRESSE1" class="inputbox" value="<?php echo MR_ENSEIGNE_ADDRESSE1 ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE3_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE3') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_ADDRESSE3" class="inputbox" value="<?php echo MR_ENSEIGNE_ADDRESSE3 ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE4_TIP')) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_ADDRESSE4') ?></td>
			<td><input type="text" name="MR_ENSEIGNE_ADDRESSE4" class="inputbox" value="<?php echo MR_ENSEIGNE_ADDRESSE4 ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_ENSEIGNE_CP_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_CP') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_CP" class="inputbox" value="<?php echo MR_ENSEIGNE_CP ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_ENSEIGNE_VILLE_TIP')) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_VILLE') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_VILLE" class="inputbox" value="<?php echo MR_ENSEIGNE_VILLE ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_ENSEIGNE_PAYS_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_PAYS') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_PAYS" class="inputbox" value="<?php echo MR_ENSEIGNE_PAYS ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip($VM_LANG->_('VM_MR_ENSEIGNE_TEL_TIP')) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_TEL') ?> (*)</td>
			<td><input type="text" name="MR_ENSEIGNE_TEL" class="inputbox" value="<?php echo MR_ENSEIGNE_TEL ?>" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_ENSEIGNE_MOBILE_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_MOBILE') ?></td>
			<td><input type="text" name="MR_ENSEIGNE_MOBILE" class="inputbox" value="<?php echo MR_ENSEIGNE_MOBILE ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell"><?php echo mm_ToolTip( $VM_LANG->_('VM_MR_ENSEIGNE_MAIL_TIP') ) ?><?php echo $VM_LANG->_('VM_MR_ENSEIGNE_MAIL') ?></td>
			<td><input type="text" name="MR_ENSEIGNE_MAIL" class="inputbox" value="<?php echo MR_ENSEIGNE_MAIL ?>" size="60" /></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
		<tr>
			<td class="labelcell">*</td>
			<td><?php echo $VM_LANG->_('VM_MR_MANDATORY') ?></td>
			<td style="width:5%;text-align:right;"></td>
		</tr>
	</table>
</div>
<fieldset>
        <legend>Tarifs</legend>
        <table id="vm_mr_rates">
            <tr>
                <th>Country codes</th>
                <th>Postcode Begin</th>
                <th>Postcode End</th>
                <th>Miniumum Weight</th>
                <th>Maximum Weight</th>
                <th>Rate</th>
                <th>Currency</th>
                <th>Vat</th>
                <th></th>
            </tr>
            <?php
            
	            $q  = "SELECT shipping_rate_id, shipping_rate_carrier, shipping_rate_country, shipping_rate_zip_start, shipping_rate_zip_end, shipping_rate_weight_start," ;		
	            $q .= "shipping_rate_weight_end, shipping_rate_value, shipping_rate_package_fee, shipping_rate_currency_id, shipping_rate_vat_id ";
	            $q .= "FROM #__{vm}_mondialrelay_shipping_rate " ;
				$q .= "WHERE shipping_rate_carrier='MONDIALRELAY' ";
				$db->query( $q ) ;
                $rates_nb = 0;
                while ($db->next_record()) {
					   $id    = $db->f('shipping_rate_id');
                       $country    = $db->f('shipping_rate_country');
                       $postcodeb  = $db->f('shipping_rate_zip_start');
                       $postcodee  = $db->f('shipping_rate_zip_end');
                       $weightmim  = $db->f('shipping_rate_weight_start');
                       $weightmax  = $db->f('shipping_rate_weight_end');
                       $fee        = $db->f('shipping_rate_package_fee');
                       $rate       = $db->f('shipping_rate_value');
                       $currency   = $db->f('shipping_rate_currency_id');
                       $vat        = $db->f('shipping_rate_vat_id');
                       $rates_nb++;
             ?>
            <tr id="vm_mr_rate_<?php echo $rates_nb ?>">
                <td>
            		<input type="hidden" name="MR_<?php echo $rates_nb ?>_ID" class="inputbox" value="<?php echo $id ?>" />
                    <select size="1" name="MR_<?php echo $rates_nb ?>_COUNTRY" class="inputbox">
                        <?php foreach($countryArray as $country_code=>$country_name) : ?>
                        <option value="<?php echo $country_code; ?>" <?php if ($country_code==$country){ echo 'selected="selected"';} ?>><?php echo $country_name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
                <td>
                    <input type="text" name="MR_<?php echo $rates_nb ?>_POSTCODEB" size="8" class="inputbox" value="<?php echo $postcodeb ?>" />
                </td>
                <td>
                    <input type="text" name="MR_<?php echo $rates_nb ?>_POSTCODEE" size="8" class="inputbox" value="<?php echo $postcodee ?>" />
                </td>
                <td>
                    <input type="text" name="MR_<?php echo $rates_nb ?>_WEIGHTMIN" size="8" class="inputbox" value="<?php echo $weightmim ?>" />
                </td>
                <td>
                    <input type="text" name="MR_<?php echo $rates_nb ?>_WEIGHTMAX" size="8" class="inputbox" value="<?php echo $weightmax ?>" />
                </td>
                <td>
                    <input type="text" name="MR_<?php echo $rates_nb ?>_RATE" size="8" class="inputbox" value="<?php echo $rate ?>" />
                </td>
                <td>
                    <select size="1" name="MR_<?php echo $rates_nb ?>_CURRENCY" class="inputbox">
                        <?php foreach($currencyArray as $currency_id=>$currency_code) : ?>
                        <option value="<?php echo $currency_id; ?>" <?php if ($currency_id==$currency){ echo 'selected="selected"';} ?>><?php echo $currency_code; ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
				<td>
				  <?php
				  require_once(CLASSPATH.'ps_tax.php');
				  ps_tax::list_tax_value("MR_".$rates_nb."_VAT", $vat) ?>
				</td>

                <td><a href="javascript:vm_mr_delete_rate(<?php echo $rates_nb ?>);">Delete</a></td>
            </tr>
        
            <?php  
                } ?>
        </table>
        <a href="javascript:vm_mr_add_rate();">Add Zone</a>
    </fieldset>
    
    <script type="text/javascript">
    var vm_mr_nb_rates = <?php echo $rates_nb ?>;
    var vm_mr_rates_tbody = $('vm_mr_rates').getFirst();
    
    
    function vm_mr_delete_rate(rateId) {
    	var rate_tr = $('vm_mr_rate_' + rateId);
    	rate_tr.setStyle('display', 'none');
    	rate_tr.getFirst().getFirst().setProperty('value', '');
    }
    
    function vm_mr_add_rate() {
    	vm_mr_nb_rates++;
        var tr = new Element('tr');
        var td1 = new Element('td');
        var td2 = new Element('td');
        var td3 = new Element('td');
        var td4 = new Element('td');
        var td5 = new Element('td');
        var td6 = new Element('td');
        var td7 = new Element('td');
        var td8 = new Element('td');
        var td9 = new Element('td');
        td1.setHTML('<input type="hidden" name="MR_'+vm_mr_nb_rates+'_ID" class="inputbox" value="new" />'+
        			'<select size="1" name="MR_'+vm_mr_nb_rates+'_COUNTRY" class="inputbox">'+
                        <?php foreach($countryArray as $country_code=>$country_name) : ?>
                        '<option value="<?php echo $country_code; ?>" <?php if ($country_code==$country){ echo 'selected="selected"';} ?>><?php echo htmlspecialchars($country_name, ENT_QUOTES); ?></option>'+
                        <?php endforeach; ?>
                    '</select>');
        td2.setHTML('<input type="text" name="MR_'+vm_mr_nb_rates+'_POSTCODEB" class="inputbox" value="<?php echo $postcodeb ?>" />');
        td3.setHTML('<input type="text" name="MR_'+vm_mr_nb_rates+'_POSTCODEE" class="inputbox" value="<?php echo $postcodee ?>" />');
        td4.setHTML('<input type="text" name="MR_'+vm_mr_nb_rates+'_WEIGHTMIN" class="inputbox" value="<?php echo $weightmim ?>" />');
        td5.setHTML('<input type="text" name="MR_'+vm_mr_nb_rates+'_WEIGHTMAX" class="inputbox" value="<?php echo $weightmax ?>" />');
        td6.setHTML('<input type="text" name="MR_'+vm_mr_nb_rates+'_RATE" class="inputbox" value="<?php echo $rate ?>" />');
        td7.setHTML('<select size="1" name="MR_'+vm_mr_nb_rates+'_CURRENCY" class="inputbox">'+
                        <?php foreach($currencyArray as $currency_id=>$currency_code) : ?>
                        '<option value="<?php echo $currency_id; ?>" <?php if ($currency_id==$currency){ echo 'selected="selected"';} ?>><?php echo $currency_code; ?></option>'+
                        <?php endforeach; ?>
                    '</select>');
        <?php
	        // Get list of tax
			$q = "SELECT `tax_rate_id`, `tax_rate`  FROM `#__{vm}_tax_rate` ORDER BY `tax_rate` DESC, `tax_rate_id` ASC" ;
			$db->query( $q ) ;
		?>
        td8.setHTML('<select size="1" name="MR_'+vm_mr_nb_rates+'_VAT" class="inputbox">'+
                        '<option selected="selected" value="0">0 (-none-)</option>'+
                        <?php while( $db->next_record() ) : ?>
                        <?$rate_int = $db->f( "tax_rate" )*100;?>
                        '<option value="<?php echo $db->f( "tax_rate_id" ); ?>"><?php echo $db->f( "tax_rate_id" ).' ('. $rate_int .'%)' ; ?></option>'+
                        <?php endwhile; ?>
                    '</select>');
        td9.setHTML('<a href="javascript:vm_mr_delete_rate('+vm_mr_nb_rates+');">Delete</a>');
        td1.inject(tr);
        td2.inject(tr);
        td3.inject(tr);
        td4.inject(tr);
        td5.inject(tr);
        td6.inject(tr);
        td7.inject(tr);
        td8.inject(tr);
        td9.inject(tr);
        tr.setProperty('id', 'vm_mr_rate_' + vm_mr_nb_rates);
        tr.inject(vm_mr_rates_tbody);
    }
    
        </script>
<?php

  		// return false if there's no configuration
   		return true;
	} //end function show_configuration

	/**
  * Returns the "is_writeable" status of the configuration file
  * @param void
  * @returns boolean True when the configuration file is writeable, false when not
  */
	function configfile_writeable() {
		return is_writeable( CLASSPATH."shipping/".$this->classname.".cfg.php" );
	} //end function configfile_writable

	/**
	* Writes the configuration file for this shipping method
	* @param array An array of objects
	* @returns boolean True when writing was successful
	*/
	function write_configuration(&$d) {
		
    	global $vmLogger;
		//write in file
        $config_file = array();
        $config_file['MR_ENSEIGNE'] = $d['MR_ENSEIGNE'];
        $config_file['MR_MARQUE'] = $d['MR_MARQUE'];
        $config_file['MR_CLE'] = $d['MR_CLE'];
        $config_file['MR_MARQUE_URL'] = $d['MR_MARQUE_URL'];
        $config_file['MR_CLE_URL'] = $d['MR_CLE_URL'];
        $config_file['MR_ENSEIGNE_ADDRESSE1'] = $d['MR_ENSEIGNE_ADDRESSE1'];
        $config_file['MR_ENSEIGNE_ADDRESSE3'] = $d['MR_ENSEIGNE_ADDRESSE3'];
        $config_file['MR_ENSEIGNE_ADDRESSE4'] = $d['MR_ENSEIGNE_ADDRESSE4'];
        $config_file['MR_ENSEIGNE_CP'] = $d['MR_ENSEIGNE_CP'];
        $config_file['MR_ENSEIGNE_VILLE'] = $d['MR_ENSEIGNE_VILLE'];
        $config_file['MR_ENSEIGNE_PAYS'] = $d['MR_ENSEIGNE_PAYS'];
        $config_file['MR_ENSEIGNE_TEL'] = $d['MR_ENSEIGNE_TEL'];
        $config_file['MR_ENSEIGNE_MOBILE'] = $d['MR_ENSEIGNE_MOBILE'];
        $config_file['MR_ENSEIGNE_MAIL'] = $d['MR_ENSEIGNE_MAIL'];
        
        //write in db 
        $config_db = array();   
        
        $config_db_new_item = array();  
        $i=1;

        while(isset($d['MR_'.$i.'_ID'])) {
        	//if display on
            if($d['MR_'.$i.'_ID']) {
                $id    = $d['MR_'.$i.'_ID'];
                $country    = $d['MR_'.$i.'_COUNTRY'];
                $postcodeb  = $d['MR_'.$i.'_POSTCODEB'];
                $postcodee  = $d['MR_'.$i.'_POSTCODEE'];
                $weightmim  = $d['MR_'.$i.'_WEIGHTMIN'];
                $weightmax  = $d['MR_'.$i.'_WEIGHTMAX'];
                $rate       = $d['MR_'.$i.'_RATE'];
                $currency   = $d['MR_'.$i.'_CURRENCY'];
                $vat        = $d['MR_'.$i.'_VAT'];
               if($id == 'new'){
               		$config_db_new_item[]=array( 'country' => $country, 'postcodeb' => $postcodeb, 'postcodee' => $postcodee, 'weightmim' => $weightmim, 'weightmax' => $weightmax, 'rate' => $rate, 'currency' => $currency, 'vat' => $vat);
               }else {
               		$config_db[$id]=array('id' => $id,'country' => $country, 'postcodeb' => $postcodeb, 'postcodee' => $postcodee, 'weightmim' => $weightmim, 'weightmax' => $weightmax, 'rate' => $rate, 'currency' => $currency, 'vat' => $vat);
               }
            }
            $i++;
        }
        
        return $this->_write_config($config_file, $config_db, $config_db_new_item);
    }
    
    private function _write_config($data, $data_db, $data_db_new_item) {
    	global $vmLogger;
        $config_file = "<?php\n";
		$config_file .= "if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); \n\n";
		foreach ($data as $key => $value)
			$config_file .= "define ('$key', '$value');\n";
		$config_file .= "?>";

		if ($fp = fopen(CLASSPATH . "shipping/" . __CLASS__ . ".cfg.php", "w")) {
			fputs($fp, $config_file, strlen($config_file));
			fclose ($fp);
			//insert db
			$db = new ps_DB;
			$q  = "SELECT shipping_rate_id, shipping_rate_carrier, shipping_rate_country, shipping_rate_zip_start, shipping_rate_zip_end, shipping_rate_weight_start," ;		
	        $q .= "shipping_rate_weight_end, shipping_rate_value, shipping_rate_package_fee, shipping_rate_currency_id, shipping_rate_vat_id ";
	        $q .= "FROM #__{vm}_mondialrelay_shipping_rate " ;
			$q .= "WHERE shipping_rate_carrier='MONDIALRELAY' ";
			$db->query( $q ) ;
			$allRates = array();
			$allRatesId = array();
            while ($db->next_record()) {
					   $id    = $db->f('shipping_rate_id');
                       $country    = $db->f('shipping_rate_country');
                       $postcodeb  = $db->f('shipping_rate_zip_start');
                       $postcodee  = $db->f('shipping_rate_zip_end');
                       $weightmim  = $db->f('shipping_rate_weight_start');
                       $weightmax  = $db->f('shipping_rate_weight_end');
                       $fee        = $db->f('shipping_rate_package_fee');
                       $rate       = $db->f('shipping_rate_value');
                       $currency   = $db->f('shipping_rate_currency_id');
                       $vat        = $db->f('shipping_rate_vat_id');
            	$rate_db[$id]=array('id' => $id, 'country' => $country, 'postcodeb' => $postcodeb, 'postcodee' => $postcodee, 'weightmim' => $weightmim, 'weightmax' => $weightmax, 'rate' => $rate, 'currency' => $currency, 'vat' => $vat);
            	$allRatesId[]=$id;
            }  
            $newRatesId = array();
            foreach($data_db as $_data){
            	$newRatesId[] = $_data['id'];
            }
              
            foreach($allRatesId as $_rateId){
            	if(in_array($_rateId, $newRatesId)){
            		//update rate
            		$this->rate_update($data_db[$_rateId]);
            	}else{
            		//delete it
            		$this->delete_rate_record($_rateId);
            	}
            }     
            //add rates
            	
            foreach($data_db_new_item as $rateToAdd){
            	$this->rate_add( $rateToAdd );
            }	
			$vmLogger->info('The Shipping Carrier has been updated.');
			return True;
		} else {
			$vmLogger->err("Error writing to configuration file");
			return (false);
		}    
	}
 //end function write_configuration
 
 /**
	 * Creates a new rate record
	 *
	 * @param array $d
	 * @return boolean
	 */
	function rate_add(&$d) {
		$db = new ps_DB;
		$timestamp = time();
		
		$fields = array('shipping_rate_name' => 'Mondial Relay standard',
								'shipping_rate_carrier' => 'MONDIALRELAY',
								'shipping_rate_country' => vmGet($d, 'country'),
								'shipping_rate_zip_start' => vmGet($d, 'postcodeb'),
								'shipping_rate_zip_end' => vmGet($d, 'postcodee'),
								'shipping_rate_weight_start' => vmGet($d, 'weightmim'),
								'shipping_rate_weight_end' => vmGet($d, 'weightmax'),
								'shipping_rate_value' => vmGet($d, 'rate'),
								'shipping_rate_currency_id' => vmGet($d, 'currency'),
								'shipping_rate_vat_id' => vmGet($d, 'vat'));
							
		$db->buildQuery('INSERT', '#__{vm}_mondialrelay_shipping_rate', $fields );
		if( $db->query() === false ) {
			$GLOBALS['vmLogger']->err( 'Failed to add the shipping rate.');
			return false;
		}
		$GLOBALS['vmLogger']->info('The shipping rate has been added.');
		
		
		return True;
	}	
		

/**
	 * Updates a rate entry
	 *
	 * @param array $d
	 * @return boolean
	 */
	function rate_update(&$d) {
    	global $vmLogger;
		$db = new ps_DB;

		$fields = array('shipping_rate_country' => vmGet($d, 'country'),
								'shipping_rate_zip_start' => vmGet($d, 'postcodeb'),
								'shipping_rate_zip_end' => vmGet($d, 'postcodee'),
								'shipping_rate_weight_start' => vmGet($d, 'weightmim'),
								'shipping_rate_weight_end' => vmGet($d, 'weightmax'),
								'shipping_rate_value' => vmGet($d, 'rate'),
								'shipping_rate_currency_id' => vmGet($d, 'currency'),
								'shipping_rate_vat_id' => vmGet($d, 'vat'));
							
		$db->buildQuery('UPDATE', '#__{vm}_mondialrelay_shipping_rate', $fields, ' WHERE shipping_rate_id=' .(int)$d["id"] );
		if( $db->query() === false ) {
			$GLOBALS['vmLogger']->err( 'Failed to update the shipping rate.');
			return false;
		}
		
		//$GLOBALS['vmLogger']->info('The shipping rate has been updated.');
		
		return True;
	}

	
   	/**
	* Controller for Deleting Shipping Rates.
	*/
	function rate_delete($record_id) {

		if (!$this->validate_rate_delete($record_id)) {
			return False;
		}
		
		return $this->delete_rate_record( $record_id );

	}
	
	/**
	* Deletes one Shipping Rate.
	*/
	function delete_rate_record( $record_id) {
		$db = new ps_DB;

		$q = 'DELETE FROM #__{vm}_mondialrelay_shipping_rate WHERE ';
		$q .= 'shipping_rate_id = '.(int)$record_id.' LIMIT 1';
		$db->query($q);
		
		return True;
	}
	
		/**
	 * Validates input parameters onBeforeShippingrateDelete
	 *
	 * @param array $d
	 * @return boolean
	 */
	function validate_rate_delete($record_id) {
		global $VM_LANG;
		if (!$record_id) {
			$d["error"] = $VM_LANG->_('PHPSHOP_ERR_MSG_SHIPPING_RATE_ID_REQ');
			return False;
		}
		return True;
	}
	
	function track($order_id) {
		global $vmLogger, $sess;
		global $VM_LANG, $mosConfig_absolute_path;

		// Read the mondialrelay configuration file
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
		
		/* Retrieve waybill information from database */
		$dbl = new ps_DB;
		$q = "SELECT tracking_number ";
		$q .= "FROM #__{vm}_shipping_label ";
		$q .= "WHERE order_id = '" . $order_id . "'";
		$dbl->query($q);
		if (!$dbl->next_record())
			return ("couldn't find label info for order #" .  $order_id);

		$tracking_number = $dbl->f('tracking_number');

		require_once(CLASSPATH . "shipping/" . __CLASS__ .
		    ".cfg.php");

		$key = '<' . trim(MR_MARQUE_URL) .'>' . $tracking_number . '<' . trim(MR_CLE_URL) . '>';
		$key = md5($key);
		
		$tracking_url = 'http://www.mondialrelay.fr/lg_fr/espaces/url/popup_exp_details.aspx?cmrq=' . strtoupper(trim(MR_MARQUE_URL)) .'&nexp=' . strtoupper($tracking_number) . '&crc=' . strtoupper($key) ;
		$tracking_msg = '<a href="'.$tracking_url.'">suivi du colis '.$tracking_number.'</a>';

		return $tracking_msg;
	}


	function void_label($order_id) {
		global $vmLogger;
		global $VM_LANG, $mosConfig_absolute_path;

		/* Remove label from shipping item.  */
		$q = "DELETE FROM #__{vm}_shipping_label ";
		$q .= "WHERE order_id = '" . $order_id . "'";

		$dbnl = new ps_DB;
		$dbnl->query($q);
		$dbnl->next_record();
		
		return ('');
	}
	
}

?>